package cc.openkit.kitwebapi.interceptor;

import cc.openkit.exception.MyException;
import cc.openkit.kitcommon.KitUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.util.*;

/**
 * 拦截器处理内容
 */

public class SignatureInterceptor implements HandlerInterceptor {

    private static String APPID = "kitappid";
    private static String APPKEY = "kitappkey";

    /**
     *
     * 时间格式 2017-03-01 22:33:23
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception{

        String app_id = request.getHeader("appid"); // 获取头部 APPID 信息
        if(!APPID.equals(app_id) ){
            throw new MyException("非法签名");
        }

        // 验证时间是否过期，时间为10分钟
        String timestamp = request.getHeader("timestamp"); // 获取头部 发送的请求时间
        if(timestamp==null || "".equals(timestamp)){
            throw new MyException("非法签名");
        }
        Date date1 = DateUtil.parse(timestamp);
        String newDate = DateUtil.now();
        Date date2 = DateUtil.parse(newDate);

        // 计算相差多少分钟
        long betweenDay = DateUtil.between(date1, date2, DateUnit.MINUTE);
        if(betweenDay>10 || betweenDay<0){
            throw new MyException("非法签名");
        }

        // 获取头部
        String signature = request.getHeader("signature"); // 获取头部的加密信息

        // 如果没有超时，那么开始循环获取所有入参
        Map<String, String> map = new HashMap<String, String>();
        Enumeration em = request.getParameterNames();
        while (em.hasMoreElements()) {
            String name = (String) em.nextElement();
            map.put(name, request.getParameter(name));
        }
        // 排序 MAP 集合
        if(KitUtil.signatureIsTrue(map, timestamp, APPKEY, signature)){
            throw new MyException("非法签名");
        }
        return true;
    }

}
